<?php
// +----------------------------------------------------------------------
// | 食得鲜 [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.shidexian.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 何锐 <poptser@foxmail.com>  [ ON THE WAY ]
// +----------------------------------------------------------------------
// | DateTime：2016-8-3 16:05:07
// +----------------------------------------------------------------------

namespace SDXApi\Controller;
use \Push\Request\V20150827 as Push;
use SDXApi\Service\SeminarService;
use Think\Controller;
use Com\TPWechat;

//use Com\TPWechat;

//信息发送API

class SmsapiController extends Controller
{
    public $options=array();
    public $sms_type = 1;
    public $sms_voice_template_id;
    public $voice_frist = 0;
    public $is_voice = 0;
    public function _initialize()
    {
        $wechat = M('wechat')->where('default_wx=1')->find();
        $this->options['token']= $wechat['token'];
        $this->options['appid']= $wechat['appid'];
        $this->options['appsecret']= $wechat['appsecret'];
        //$this->init_ucuser();
    }
    /**
     * 测试发送短信
     * @return bool
     */
    public function test_push(){

        $url = "http://localhost:82/index.php?s=/Smsapi/send_message_url";
        $data['message_code'] =  'order_refund';
        $data['user_phone'] =  15820245055;
        $data['user_name'] =  "何锐";
        $data['order_sn'] =  "这里是订单号";
        $data['user_rank'] =  0;
        $data['ver_code'] = 0 ;
        $data['user_id'] =  1;
        $post['data'] = json_encode($data);
        $re = http_post($url,$post);

        if($re){
            dump("ok");
        }else{
            dump("fail");
        }

    }
    public function index(){

    }
    /**
     *发送短信请求API URL
     */
    public function send_message_url(){

        $get_data = $_POST['data'];
        $Json_Data = json_decode($get_data, true);    //JSON 编码
        $R = $this->send_message_api($Json_Data['message_code'],$Json_Data['user_phone'],$Json_Data['user_name'],$Json_Data['user_rank'],$Json_Data['order_sn'],$Json_Data['ver_code'],$Json_Data['user_id'],$Json_Data['remark'],$Json_Data['meting_time'],$Json_Data['wechat_param'],$Json_Data['louxiaoer']);

        if($R){
            //w_log("log","返回成功状态");
            exit(json_encode(array('state' => 1)));
        }else{
            //w_log("log","返回失败状态");
            exit(json_encode(array('state' => 0)));
        }
    }

    /**
     *发送微信和APP请求API URL
     */
    public function send_app_wechat_url(){

        $get_data = $_POST['data'];
        $Json_Data = json_decode($get_data, true);    //JSON 编码

        $R = $this->send_app_wechat_api($Json_Data['message_code'],$Json_Data['user_id'],$Json_Data['param']);

        if($R){
            //w_log("log","返回成功状态");
            exit(json_encode(array('state' => 1)));
        }else{
            //w_log("log","返回失败状态");
            exit(json_encode(array('state' => 0)));
        }
    }

    /**
     * 微信和APP推送
     * @param String $message_code
     * @param String $user_id
     * @param array $param
     */
    public function send_app_wechat_sms_api($message_code,$user_id,$param=array(),$param_voice=array(),$wechat_param=array(),$wechat_url='',$message_log_id,$template_id,$phone){

        $mail_templates = S('mail_templates_'.$message_code);
        if(!$mail_templates){
            $mail_templates = M("mail_templates")->where(array("template_code"=>$message_code))->find();
            S('mail_templates_'.$message_code,$mail_templates,60);
        }

        //微信推送
        if(in_array("3",explode(",",$mail_templates['msg_type']))){

            $wechat_send_state=$this->wechat_template_send($user_id, $wechat_param,$mail_templates,$wechat_url,$message_log_id);
            if($wechat_send_state){
                return true;
            }
        }

        //APP推送
        if(in_array("4",explode(",",$mail_templates['msg_type']))){
            $this->app_push($user_id, $param,$mail_templates,$message_log_id);
        }

        if(in_array("1",explode(",",$mail_templates['msg_type']))){
            $message_res = false;
            $send_data = false;
            if($this->sms_type==1){
                $send_data = $this->send_message_api_netease($template_id,$phone,$param);
                $message_res = true;
            }elseif($this->sms_type==2){
                if($this->is_voice==1){
                    $send_data = $this->send_voice_message_api_taobao($this->sms_voice_template_id,$phone,$param_voice);
                    if($send_data){
                        $this->update_message_log($message_log_id,'voice_state', 1);
                    }else{
                        $this->update_message_log($message_log_id,'voice_state', 0);
                    }
                }else{
                    $send_data = $this->send_message_api_taobao($template_id,$phone,$param);
                    $message_res = true;
                }

//                $code_time = S('phone_code_send_time'.$user_id);
//                if($this->voice_frist && (empty($code_time) || $code_time==0)){
//                    $send_data = $this->send_voice_message_api_taobao($this->sms_voice_template_id,$phone,$param_voice);
//                    if($send_data){
//                        $this->update_message_log($message_log_id,'voice_state', 1);
//                    }else{
//                        $this->update_message_log($message_log_id,'voice_state', 0);
//                    }
//                    $code_time+=1;
//                    S('phone_code_send_time'.$user_id,$code_time,300);
//                }
//                //如果语音通知请求失败，则发送短信通知
//                if(!$send_data && $code_time>0){
//                    $send_data = $this->send_message_api_taobao($template_id,$phone,$param);
//                    $message_res = true;
//                    S('phone_code_send_time'.$user_id,null);
//                }
            }
            if($send_data && $message_res){
                $this->update_message_log($message_log_id,'state', 1);
            }else{
                $this->update_message_log($message_log_id,'state', 0);
            }
        }

        return true;

    }

    public function send_message_api_asyn($message_code, $user_phone, $user_name =0, $user_rank =0, $order_sn='', $ver_code=0,$user_id=0,$remark = array(),$meting_time=null,$wechat_param=array(),$louxiaoer=array(),$bonus_type_id=0){

        $Json_Data=array();
        $Json_Data['message_code']=$message_code;
        $Json_Data['user_phone']=$user_phone;
        $Json_Data['user_name']=$user_name;
        $Json_Data['user_rank']=$user_rank;
        $Json_Data['order_sn']=$order_sn;
        $Json_Data['ver_code']=$ver_code;
        $Json_Data['user_id']=$user_id;
        $Json_Data['remark']=$remark;
        $Json_Data['meting_time']=$meting_time;
        $Json_Data['wechat_param']=$wechat_param;
        $Json_Data['louxiaoer']=$louxiaoer;
        $Json_Data['bonus_type_id']=$bonus_type_id;
        
        $data=json_encode($Json_Data);
        
        $method ='POST';
        $host=$_SERVER['HTTP_HOST'];
        $fp = fsockopen($host, 80, $errno, $errstr, 10);
        if ($fp){
            $url='/index.php?s=/Smsapi/send_message_api_asyn_do';
            $posts =array(
                'data'=>$data
            );

            $postValues='';
            if ( is_array( $posts ) ) {
                foreach( $posts AS $name => $value ){
                    $postValues .= '&'.urlencode( $name ) . "=" . urlencode( $value );
                }
            }

            $url.=$postValues;
            $http = "$method $url HTTP/1.1\r\n";
            $http .= "Host: $host\r\n";
            $http .= "Connection: Close\r\n\r\n";
            fwrite($fp,$http);
            fclose($fp);
        }
    }

    public function send_message_api_asyn_do(){
        $get_data = $_REQUEST['data'];
        $Json_Data = json_decode($get_data, true);    //JSON 编码

        $message_code=$Json_Data['message_code'];
        $user_phone=$Json_Data['user_phone'];
        $user_name=$Json_Data['user_name'];
        $user_rank=$Json_Data['user_rank'];
        $order_sn=$Json_Data['order_sn'];
        $ver_code=$Json_Data['ver_code'];
        $user_id=$Json_Data['user_id'];
        $remark=$Json_Data['remark'];
        $meting_time=$Json_Data['meting_time'];
        $wechat_param=$Json_Data['wechat_param'];
        $louxiaoer=$Json_Data['louxiaoer'];
        $bonus_type_id=$Json_Data['bonus_type_id'];

        $message_log_id=$this->send_message_api($message_code, $user_phone, $user_name, $user_rank, $order_sn, $ver_code,$user_id,$remark,$meting_time,$wechat_param,$louxiaoer);
        if($message_log_id && $bonus_type_id!=''){
            M("message_log")->where(array("message_id"=>$message_log_id))->save(array("bonus_type_id"=>$bonus_type_id));
        }
    }

    protected $additional='';

    /**
     * 发送短信API
     * @param $message_code
     * @param $user_phone
     * @param null $user_name
     * @param int $user_rank
     * @param null $order_sn
     * @param null $ver_code
     * @return bool
     * @throws Exception
     */
    public function send_message_api($message_code, $user_phone, $user_name =0, $user_rank =0, $order_sn='', $ver_code=0,$user_id=0,$remark = array(),$meting_time=null,$wechat_param=array(),$louxiaoer=array()){

        if(!empty($order_sn)){
            $best_time = M("order_info")->where(array("order_sn"=>$order_sn))->getField("best_time");
            if(!empty($best_time)){
                if(time()-$best_time>2640000){
                    //有订单号，且收货时间已经超过30天，任何操作将不发送信息
                    return true;
                }
            }
        }

        //不发送短信
        $no_send = array(
            18028582275,18820013479,18903012888,13423621976,13922303379,13533589508,
            13435247596,18588734970,15989012380,15920425953,13286800382,13074215090,
            13926192875,18825163342,18588677281,13580513360,13570495884,15915818502,
            18926152533
        );
        if(in_array($user_phone,$no_send)){
            return true;
            exit;
        }

        if(!empty($user_id)){
            $data = M("blacklist")->where(array('blacklist_type'=>'1','user_id'=>$user_id))->find();
            if($data){
                return true;
                exit();
            }
        }

        ///
        if(!empty($order_sn)){
            $data = M("order_info")->where(array('add_time'=>array('lt','1472400001'),'order_sn'=>$order_sn))->find();
            //判断此订单 是否创建时间早于 2016/8/29 0:00:01
            if($data){
                return true;
                exit();
            }
        }

        if($remark['additional']){
            $this->additional = $remark['additional'];
        }

        $phone = array($user_phone);
        $title='';

        //send_message_api_netease
        switch ($message_code){
            case "goods_depreciate":
                $template_id = 3110085;
                $param =array($user_name,$remark['goods_price']);
                $action = "hey，".$user_name."！你订阅的".$remark['goods_price']."已经降价了诶！赶紧去下单吧，要不然降价很快就被人买完了。抓紧上去微信公众号“食得鲜”或者APP看看吧。";
                break;
            case "wechat_share_bonus_notice":
                $template_id = 0;
                $param =array();
                $action = "";
                break;
            case "share_inviter_bonus_notice":
                $template_id = 3063191;
                $param =array($remark['invited_nickname']);
                $action = "不等过年照样拿红包！您已成功邀请一位好友".$remark['invited_nickname']."来食得鲜签到，您和好友均可获得邀请奖励280元红包！速速登录食得鲜商城拆红包，买买买才购嗨！";
                //不等过年照样拿红包！您已成功邀请一位好友%s来食得鲜签到，您和好友均可获得邀请奖励280元红包！速速登录食得鲜商城拆红包，买买买才购嗨！
                break;
            case "share_invited_bonus_arrived":
                $template_id = 3054816;
                $param =array($user_name,$remark['bonus_name'],$remark['bonus_ad']);
                $action = "尊敬的".$user_name."，送您".$remark['bonus_name']."的红包赶紧收起来！".$remark['bonus_ad']."您尽管买买买，我负责送货到家！";
                //尊敬的{微信用户名}，送您一个 满{金额}减{金额}/{折扣}的红包赶紧收起来！{让钱包不再悲伤，解开封印不！忍！了！}您尽管买买买，我负责送货到家！
                break;
            case "order_overtime_compensate":
                $template_id = 3127397;
                $param =array($remark['compensate_money']);
                $action = "尊敬的食得鲜用户，您的订单超时送达，我们深表歉意。根据您的实际支付金额的免单补偿{{$remark['compensate_money']}}已发放到您的账户余额中，请前往我的-账户账户余额中查看。感谢您一如既往的支持食得鲜！";
                break;
            case "d12_bonus_notice":
                $template_id = 3126022;
                $param =array($remark['bonus_title'],$remark['bonus_ad']);
                $action = $remark['bonus_title']."大圣就是任性，一言不合又撒福利了".$remark['bonus_ad'];
                //%s大圣就是任性，一言不合又撒福利了%s
                break;
            case "bonus_arrived":
                //评价201702
                $template_id = 0;
                $param =array();
                $action = "";
                break;
            case "bonus_expired_reminder":
                //评价201702
                $template_id = 3060612;
                $param =array($user_name,'满'.$remark['min_amount']."减".$remark['bonus_money'],$remark['date']);
                $action = "嗨，".$user_name."，你有满".$remark['min_amount']."减".$remark['bonus_money']."优惠券将于".$remark['date']."到期，请及时使用。详情登录食得鲜公众号或APP“我的红包”查看。";

                break;
            case "evaluate_sendredbag":
                //评价201702
                $template_id = 3063222;
                $remark['remark']='，7天内使用有效。签到送钱活动进行中，记得每天回来看看哟~';
                $param =array($remark['remark']);

                $action = "感谢您的评价分享！评价红包已发放至您账户".$remark['remark'];

                break;
            case "comment_201702":
                //评价201702
                $template_id = 3055288;
                $param =array($user_name,$remark['goods_name'],$remark['goods_number'],$remark['msg_opt'],urldecode($remark['url']));

                $action = "尊敬的".$user_name.",您的商品".$remark['goods_name']."等".$remark['goods_number']."件宝贝到手还满意吗？夸我我不会骄傲，提意见会让我更好！".$remark['msg_opt']."点击此链接一键直达评价%s".$remark['url'];

                break;
            case "Recharge_gift":
                //充值赠送
                $template_id = 3039119;
                $param =array($user_name,$remark['amount'],$remark['gift']);

                $action = "
尊敬的".$user_name."，您的账户已成功充值".$remark['amount']."，赠送".$remark['gift']."，请在微信公众号联系客服，赠品将为您送货上门，感谢您使用食得鲜";
                break;
            case "Recharge_1000":
                //圣诞充值1000
                $template_id = 3037070;
                $param =array($user_name,$remark['amount']);
                $action = "
尊敬的".$user_name."，您的账户已成功充值".$remark['amount']."，赠送有机鸭稻米5斤+299元埃沃领带定制一条，请在微信公众号联系客服，赠品将为您送货上门，感谢您使用食得鲜";
                break;
            case "Recharge_2980":
                //圣诞充值2980
                $template_id = 3037071;
                $param =array($user_name,$remark['amount']);
                $action = "尊敬的".$user_name."，您的账户已成功充值".$remark['amount']."，赠送神灯机器人或魔镜机器人，以及赠送有机鸭稻米10斤+1件价值599元埃沃衬衫定制券，请在微信公众号联系客服，赠品将为您送货上门，感谢您使用食得鲜";
                break;
            case "Recharge_9800":
                //圣诞充值9800
                $template_id = 3031726;
                $param =array($user_name,$remark['amount']);
                $action = "尊敬的".$user_name."，您的账户已成功充值".$remark['amount']."，赠送小宝机器人，以及有机鸭稻米20斤+3件价值599元埃沃衬衫定制券，请在微信公众号联系客服，赠品将为您送货上门，感谢您使用食得鲜";
                break;
            case "order_warning_new":
                //自提1天未领取提醒
                /*$template_id = 3030506;
                $param =array($user_name,substr($order_sn,-8),$meting_time);
                $wid=M("order_info")->where("order_sn='$order_sn'")->getField("wid");
                $wid_info=D("orderinfo")->get_wid_info($wid);
                $action = "尊敬的".$user_name."，您昨天有一份自提订单".substr($order_sn,-8)."未领取，请于".$meting_time."前往门店领取，逾期系统将自动为您取消订单。门店地址：".$wid_info['sender_address'].$wid_info['sender'];*/

                $template_id = 3129317;
                $wid=M("order_info")->where("order_sn='$order_sn'")->getField("wid");
                $wid_info=D("orderinfo")->get_wid_info($wid);
                $param =array($user_name,substr($order_sn,-8),$meting_time,$wid_info['sender_address'].$wid_info['sender']);
                $action = "尊敬的".$user_name."，您昨天有一份自提订单".substr($order_sn,-8)."未领取，请于".$meting_time."前往门店领取，逾期系统将自动为您取消订单。门店地址：".$wid_info['sender_address'].$wid_info['sender'];
                break;
            case "order_remind_new":
                //自提未领取提醒
                /*$template_id = 3030504;
                $param =array($user_name,substr($order_sn,-8),$meting_time);
                $wid=M("order_info")->where("order_sn='$order_sn'")->getField("wid");
                $wid_info=D("orderinfo")->get_wid_info($wid);
                $action = "尊敬的".$user_name."，您今天有一份自提订单".substr($order_sn,-8)."未领取，请于".$meting_time."前往门店领取，逾期系统将自动为您取消订单。门店地址：".$wid_info['sender_address'].$wid_info['sender'];*/

                $template_id = 3142301;
                $wid=M("order_info")->where("order_sn='$order_sn'")->getField("wid");
                $wid_info=D("orderinfo")->get_wid_info($wid);
                $param =array($user_name,substr($order_sn,-8),$meting_time,$wid_info['sender_address'].$wid_info['sender']);
                $action = "尊敬的".$user_name."，您今天有一份自提订单".substr($order_sn,-8)."未领取，请于".$meting_time."前往门店领取，逾期系统将自动为您取消订单。门店地址：".$wid_info['sender_address'].$wid_info['sender'];
                break;
            case "order_booking_self_new":
                //预售单自提（新）
                /*$template_id = 3032504;
                $param =array($user_name,substr($order_sn,-8),$remark['time']);
                $wid=M("order_info")->where("order_sn='$order_sn'")->getField("wid");
                $wid_info=D("orderinfo")->get_wid_info($wid);
                
                $action = "尊敬的".$user_name."，您的订单尾号".substr($order_sn,-8)."包含预售商品，请于".$remark['time']."前往门店领取，逾期系统将自动为您取消订单。门店地址：".$wid_info['sender_address'].$wid_info['sender'];*/

                $template_id = 3130392;
                $wid=M("order_info")->where("order_sn='$order_sn'")->getField("wid");
                $wid_info=D("orderinfo")->get_wid_info($wid);

                $param =array($user_name,substr($order_sn,-8),$remark['time'],$wid_info['sender_address'].$wid_info['sender']);
                $action = "尊敬的".$user_name."，您的订单尾号".substr($order_sn,-8)."已支付成功，请于".$remark['time']."前往门店领取，逾期系统将自动为您取消订单。门店地址：".$wid_info['sender_address'].$wid_info['sender'];
                break;
            case "order_pay_ok_self_new":
                //支付成功-自提(新)
                /*$template_id = 3062387;
                $wid=M("order_info")->where("order_sn='$order_sn'")->getField("wid");
                $wid_info=D("orderinfo")->get_wid_info($wid);

                $param =array($user_name,substr($order_sn,-8),$remark['time'],$remark['receipt_code']);
                $action = "尊敬的".$user_name."，您的订单尾号".substr($order_sn,-8)."已支付成功，请于".$remark['time']."前往门店领取，逾期系统将自动为您取消订单。自提时请向收银员出示提货码".$remark['receipt_code']."。门店地址：".$wid_info['sender_address'].$wid_info['sender'];*/

                $template_id = 3130392;
                $wid=M("order_info")->where("order_sn='$order_sn'")->getField("wid");
                $wid_info=D("orderinfo")->get_wid_info($wid);

                $param =array($user_name,substr($order_sn,-8),$remark['time'],$wid_info['sender_address'].$wid_info['sender']);
                $action = "尊敬的".$user_name."，您的订单尾号".substr($order_sn,-8)."已支付成功，请于".$remark['time']."前往门店领取，逾期系统将自动为您取消订单。门店地址：".$wid_info['sender_address'].$wid_info['sender'];
                break;
            case "order_confirm_sendmsg":
                //收货成功后的2小时后发送
                $template_id = 3030232;
                $param =array($user_name,$order_sn,urldecode($remark['url']));
                $action = "尊敬的".$user_name."，您的订单".$order_sn."已显示签收，如您对商品满意请告诉我们，如不满意请告诉大家，食得鲜让您的生活领鲜一步，健康领先一大步！点击链接".$remark['url'];
                break;
            case "activity_60_100_arrived":
                //充60送100支付通知
                $template_id = 3033328;
                $param =array($user_name,$remark['amount']);
                $action = "尊敬的".$user_name."，您的账户已成功充值".$remark['amount']."，请到“我的余额”中查看，感谢您使⽤⾷得鲜";
                break;
            case "activity_60_100":
                //充60送100支付通知
                $template_id = 3034322;
                $param =array($user_name,$remark['amount']);
                $action = "尊敬的".$user_name."，您的账户充值已成功，该活动充值的".$remark['amount']."将在11月16号到账，请关注账户余额变动，感谢您使食得鲜";
                break;
            case "goods_arrive_favorite":
                //到货通知
                $template_id = 3034127;
                $param =array($user_name,$remark['goods_name']);
                $action = "尊敬的".$user_name.",您登记的".$remark['goods_name']."已到货，已自动将该商品加入收藏，欢迎前往食得鲜购买。";
                //尊敬的%s,您所订购的商品已成功支付，订单号:%s,请耐心等待配送
                break;
            case "order_pay_ok":
                //订单支付成功
                $template_id = 3031023;
                if(gmtime()>local_mktime(0,0,0,1,27,2017) && gmtime()<local_mktime(0,0,0,2,3,2017)){
                    $order_sn.='，春节假期，可能稍有晚点，配送员已在快马加鞭';
                }
                $param =array($user_name,$order_sn);
                $action = "尊敬的".$user_name.",您所订购的商品已成功支付，订单号:".$order_sn.",请耐心等待配送";
                //尊敬的%s,您所订购的商品已成功支付，订单号:%s,请耐心等待配送
                break;
            case "order_distribution":
                $template_id = 3031024;
                $param =array($user_name,$order_sn);
                $action = "尊敬的".$user_name."，您的订单:".$order_sn."已经在配送中，请保持手机畅通。";
                //订单开始配送
                break;
            case "order_finish":
                $template_id = 3060154;
                $order_id=M("order_info")->where(array('order_sn'=>$order_sn))->getField("order_id");

                $louxiaoer_info=$this->get_louxiaoer_info($order_id);

                $remark['housekeeper']=$remark['overtimeBonus'];
                /*if(!empty($louxiaoer_info['name']) && !empty($louxiaoer_info['phone'])){
                    $remark['housekeeper'].="添加楼管家微信".$louxiaoer_info['name']."-".$louxiaoer_info['phone']."还能最高返8元。";
                }else{
                    $remark['housekeeper'].="联系楼管家还能再返现。如需添加，请于微信公众号留言。";
                }*/

                $goods_name=M("order_goods")->where(array('order_id'=>$order_id,'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$order_id.')')))->limit(1)->getField("goods_name");
                $goods_number=M("order_goods")->where(array('order_id'=>$order_id,'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$order_id.')')))->count();


                $param =array($user_name,$goods_name,$goods_number,$remark['housekeeper']);
                //$action = "尊敬的".$user_name.",您所订购的商品订单号".$order_sn."已经成功送达，食得鲜祝您生活愉快";
                $action = "尊敬的".$user_name.",您所订购的".$goods_name."等".$goods_number."件商品已经成功送达，".$remark['housekeeper']."祝生活愉快！";
                //订单完成
                //尊敬的%s,您所订购的商品订单号:%s已经成功送达，食得鲜祝您生活愉快
                break;
            case "order_finish_self":
                $template_id = 3029155;
                $param =array($user_name,$order_sn);

                $action = "尊敬的".$user_name.",您所订购的商品订单号".$order_sn."已经自提取货，食得鲜祝您生活愉快";
                //订单完成
                //尊敬的%s,您所订购的商品订单号%s已经自提取货，食得鲜祝您生活愉快
                break;
            case "order_refund":
                $template_id = 3031025;
                $param =array($user_name,$order_sn);
                $action = "尊敬的".$user_name.",您的退货退款已经成功(订单号:".$order_sn.")，请注意查收退款消息";
                //订单退款
                break;
            case "ver_code":
                $this->sms_type = C('SMS_TYPE');
                if($this->sms_type==1){
                    $template_id = 3032025;
                    $param =array($ver_code);
                    $action = "短信验证码,验证码:".$ver_code;
                }else{
                    if(!empty($remark['is_voice'])){
                        $this->is_voice = 1;
                    }

                    $this->voice_frist=1;
                    $template_id = 'SMS_56995153';      //短信模板id
                    $this->sms_voice_template_id = 'TTS_56705601';      //文本转语音通知模板id
                    $param_voice =array('name'=>$ver_code);
                    $action['send_voice_content'] = "您的验证码为：".$param_voice['name']."，感谢您的关注";
                    $param =array('number'=>$ver_code,'acknowledgments'=>C('SMS_CONTENT'));
                    $action['send_content'] = "亲爱的用户，您本次的验证码为：".$param['number']."，为了您的账户安全，请勿将验证码告诉他人，若非您本人操作请忽略。".$param['acknowledgments']."感谢您的支持！";
                }
                //短信验证码
                break;
            case "shipping_start_notice" :
                $template_id = 3058129;
                $order_id=M("order_info")->where(array('order_sn'=>$order_sn))->getField("order_id");

                $louxiaoer_info=$this->get_louxiaoer_info($order_id);
                $remark['louxiaoer']='';
                /*if(!empty($louxiaoer_info['name']) && !empty($louxiaoer_info['phone'])){
                    $remark['louxiaoer']="您的楼管家为".$louxiaoer_info['name'].'-'.$louxiaoer_info['phone']."，加微信能再返现。";
                }else{
                    $remark['louxiaoer']="加楼管家微信还能再返现，如需添加，请于微信公众号留言。";
                }*/

                $goods_name=M("order_goods")->where(array('order_id'=>$order_id,'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$order_id.')')))->limit(1)->getField("goods_name");
                $goods_number=M("order_goods")->where(array('order_id'=>$order_id,'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$order_id.')')))->count();
                $goods_l=$goods_name."等".$goods_number."件";
                $param = array($user_name,$goods_l,$remark['phone'],$remark['best_time'],$remark['louxiaoer']);

                $action = "
尊敬的".$user_name."，您的商品".$goods_l."已经在配送中，配送员".$remark['phone']."，预计到达时间为".$remark['best_time']."，请保持手机畅通。".$remark['louxiaoer']."祝生活愉快！";

                //尊敬的%s，您的商品%s已经在配送中，配送员%s，预计到达时间为%s，请保持手机畅通。您的专属客服楼管家为%s，祝生活愉快！
                break;

            case "distribute_start" :
                $template_id = 3031156;
                if(gmtime()>local_mktime(0,0,0,1,27,2017) && gmtime()<local_mktime(0,0,0,2,3,2017)){
                    $remark['best_time'].='，春节假期，可能稍有晚点，配送员已在快马加鞭';
                }
                $param = array($user_name,$order_sn,$remark['best_time']);
                $action = "尊敬的".$user_name."，您的订单".$order_sn."已经在配送中，预计到达时间".$remark['best_time']."，请保持手机畅通。";
                //尊敬的%s，您的订单%s已经在配送中，预计到达时间%s，请保持手机畅通。
                break;
            case "shipping_pickup_notice":
                $template_id = 3029083;
                $param =array($user_name,$remark['take_no'],$remark['meet_time'],$remark['meet_address'],$remark['phone']);
                $action = "尊敬的".$user_name."，您的取件号为".$remark['take_no']."，请".$remark['meet_time']."分钟内到".$remark['meet_address']."取件。配送员".$remark['phone'];
                //尊敬的%s，您的取件号为%s，请%s分钟内到%s取件。配送员%s
                break;
            case "shipping_arrive_notice":
                $template_id = 3032058;
                $param =array($order_sn,$remark['meet_time'],$remark['meet_address'],$remark['shipper_moblie']);
                $action = "您好，您的取件号为".$order_sn."，请".$remark['meet_time']."分钟内到".$remark['meet_address']."取件。配送员".$remark['shipper_moblie'];
                break;
            case "order_remind":
                $template_id = 3030082;
                $param =array($user_name,$order_sn,$meting_time);
                $action = "尊敬的".$user_name."，您今天有一份自提订单".$order_sn."未领取，请于".$meting_time."之前前往领取";
                //尊敬的%s，您今天有一份自提订单%s未领取，请于%s之前前往领取。
                break;
            case "order_warning":
                $template_id = 3032056;
                $param =array($user_name,$order_sn,$meting_time);
                $action = "尊敬的".$user_name."，您今天有一份自提订单".$order_sn."，请于".$meting_time."之前前往领取，过时将自动取消订单";
                //尊敬的%s，您昨天有一份自提订单%s未领取，请于%s之前前往领取，过时将自动取消订单。
                break;
            case "order_cancel":
                $template_id = 3032057;
                $param =array($user_name,$order_sn);
                $action = "尊敬的".$user_name."，由于您过时仍未领取自提订单".$order_sn."，该订单已经取消。";
                //尊敬的%s，由于您过时仍未领取自提订单%s，该订单已经取消。
                break;
            case "order_pay_ok_distribute":
                $template_id = 3063131;
                $order_id=M("order_info")->where(array('order_sn'=>$order_sn,'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$order_id.')')))->getField("order_id");

                $goods_name=M("order_goods")->where(array('order_id'=>$order_id,'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$order_id.')')))->limit(1)->getField("goods_name");
                $goods_number=M("order_goods")->where(array('order_id'=>$order_id))->count();

                $remark['housekeeper'] = $this->additional ? $this->additional : '';

                $param =array($user_name,$goods_name,$goods_number,$remark['best_time'],$remark['housekeeper']);
                $action = "尊敬的".$user_name."，您所订购的商品".$goods_name."等".$goods_number."件已支付成功，预计配送时间".$remark['best_time']."，请耐心等待配送。".$remark['housekeeper'];
                //尊敬的%s，您所订购的商品已支付成功，订单号%s，预计配送时间%s，请耐心等待配送。
                break;
            case "order_pay_ok_distribute_lou":
                $template_id = 3063132;
                $order_id=M("order_info")->where(array('order_sn'=>$order_sn))->getField("order_id");
                $louxiaoer_info=$this->get_louxiaoer_info($order_id);

                $remark['housekeeper'] = $this->additional ? $this->additional : '';
                $goods_name=M("order_goods")->where(array('order_id'=>$order_id,'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$order_id.')')))->limit(1)->getField("goods_name");
                $goods_number=M("order_goods")->where(array('order_id'=>$order_id,'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$order_id.')')))->count();

                $param =array($user_name,$goods_name,$goods_number,$remark['best_time'],$remark['housekeeper']);
                $action = "尊敬的".$user_name."，您所订购的商品".$goods_name."等".$goods_number."件已支付成功，预计配送时间".$remark['best_time']."，请耐心等待配送。";

                //$param =array($user_name,$order_sn,$remark['best_time'],$louxiaoer['name'].$louxiaoer['phone']);
                //$action = "尊敬的".$user_name."，您所订购的商品已支付成功，订单号".$order_sn."，预计配送时间".$remark['best_time']."，请耐心等待配送。您的专属客服楼管家为".$louxiaoer['name'].$louxiaoer['phone']."，任何订单问题，可电话或微信联系楼管家为您解决。祝生活愉快！";
                //尊敬的%s，您所订购的商品已支付成功，订单号%s，预计配送时间%s，请耐心等待配送。您的专属客服楼管家为%s，任何订单问题，可电话或微信联系楼管家为您解决。祝生活愉快！
                break;
            case "louxiaoer_warning":
                $template_id = 3061068;
                $louxiaoer['phone'].="添加楼管家微信下单还能再返现";
                $param =array($user_name,$louxiaoer['name'].$louxiaoer['phone']);
                $action = "尊敬的".$user_name."，您的专属客服楼管家为".$louxiaoer['name'].$louxiaoer['phone']."，任何订单问题，可电话或微信联系楼管家为您解决。祝生活愉快！";
                //尊敬的%s，您的专属客服楼管家为%s，任何订单问题，可电话或微信联系楼管家为您解决。祝生活愉快！
                break;
            case "order_pay_ok_self":
                $template_id = 3029176;
                $param =array($user_name,$order_sn);
                $action = "尊敬的".$user_name."，您所订购的商品订单号".$order_sn."已支付成功，门店地址请查看订单详情，请尽快前往取货。";
                //尊敬的%s，您所订购的商品订单号%s已支付成功，门店地址请查看订单详情，请尽快前往取货。
                break;
            case "goods_arrive":
                $template_id = 3034127;
                $param =array($user_name);
                $action = "尊敬的".$user_name."，您登记的".$remark['goods_name']."已到货，欢迎前往⾷食得鲜购买";
                //尊敬的%s，您登记的%s已到货，欢迎前往⾷食得鲜购买。
                break;
            case "describe_order_notice":
                $template_id = 3031270;
                $param =array($user_name,$order_sn);
                $action = "尊敬的".$user_name."，您的订单".$order_sn."配送员无法与您取得联系已延迟发货，请于到微信公众号与客服联系修改配送时间，或拨打客服电话400-830-2108";
                //尊敬的%s，您的订单%s配送员无法与您取得联系已延迟发货，请于到微信公众号与客服联系修改配送时间，或拨打客服电话400-830-2108
                break;
            case "delayed_delivery_notice":
                $template_id = 3029241;
                if(gmtime()>local_mktime(0,0,0,1,27,2017) && gmtime()<local_mktime(0,0,0,2,3,2017)){
                    $remark['best_time'].='，春节假期，可能稍有晚点，配送员已在快马加鞭';
                }
                $param =array($user_name,$order_sn,$remark['best_time']);
                $action = "尊敬的".$user_name."，您的订单".$order_sn."延迟配送的时间为".$remark['best_time']."，请耐心等待配送";
                //尊敬的%s，您的订单%s延迟配送的时间为%s，请耐心等待配送。
                break;
            case "order_cancel_pickup":
                $template_id = 3032057;
                $param = array($user_name, $order_sn);
                $action = "尊敬的{$user_name}，您的订单{$order_sn}已取消，退款将在1-3个工作日内退回您的账户，请注意查收，欢迎再次光临食得鲜";
                break;
            case 'order_pickup_warning_new':
                $template_id = 3036033;
                $wid=M("order_info")->where("order_sn='$order_sn'")->getField("wid");
                $wid_info=D("orderinfo")->get_wid_info($wid);
                if($wid!='8'){
                    return true;
                    exit();
                }
                $param = array($user_name,substr($order_sn,-8),$meting_time);
                $action = "尊敬的{$user_name}，您昨天有一份自提订单{$order_sn}未领取，请于{$meting_time}前往门店领取，今天内未领取系统将自动为您取消订单。门店地址：".$wid_info['sender_address'].$wid_info['sender'];
                break;

            case 'buy_now_notice':
                $template_id = 3034583;
                $param = array($user_name,$remark['goods_name']);
                $action = "尊敬的{$user_name}，您订阅的{$remark['goods_name']}在5分钟后开始秒杀，赶紧上食得鲜提前加入购物车吧!";
                break;
            case 'order_refund_new':
                $template_id = 3063224;//缺货退款操作发送该短信：
                $order_id=M("order_info")->where(array('order_sn'=>$order_sn))->getField("order_id");
                $goods_name=M("order_goods")->where(array('order_id'=>$order_id))->group("order_id")->getField("group_concat(goods_name)");
                if(mb_strlen($goods_name,'utf-8')>30){
                    $goods_name=mb_substr($goods_name,0,26,"utf-8").'...';
                }

                $param = array($user_name,$remark['goods_name'],$remark['refund_amount']);
                $action = "尊敬的{$user_name}，您购买的商品{$remark['goods_name']}缺货为您退款，更多信息请查看订单详情，抱歉给您带来不便，退款金额{$remark['refund_amount']}将在1-3个工作日内返回到您的原支付账户，请注意查收。";
                break;
            case 'order_refund_new_t':
                $template_id = 3063225;//漏送、次品、退货、直接退款操作发送该短信  ：
                //$goods_number=M("order_goods")->where(array('order_id'=>$order_id))->count();

                $param = array($user_name,$remark['goods_name'],$remark['refund_amount']);
                $action = "尊敬的{$user_name}，您购买{$remark['goods_name']}商品为您退款，退款商品信息请查看订单详情，抱歉给您带来不便，退款金额{$remark['refund_amount']}将在1-3个工作日内返回到您的原支付账户，请注意查收。";
                break;
            case 'order_pay_ok_store':
                $template_id = 3061187;
                $user_name = '会员';
                $remark2='在微信公众号商城或APP下单，珠江新城为您一小时内送货上门。';
                $param = array($user_name,$remark['order_amount'],$remark2);
                $action = "尊敬的{$user_name}，您在食得鲜体验中心消费支付了{$remark['order_amount']}元，{$remark2}感谢您的惠顾！";
                break;
            case 'daily_rewards':
                //登录奖励@poptser
                if($user_phone==18320408956){
                    return true;
                }
                $template_id =3052159;
                $param = array($user_name,$remark['goods_title']);
                $action = "{$user_name}奉天承运,大圣诏曰:爱卿克己尽职,现将登录俸禄发放,速速前往「我的红包」里查收,钦此{$remark['goods_title']}";
                break;
            case 'urge_online':
                //提醒上鲜@poptser
                if($user_phone==18320408956){
                    return true;
                }
                $template_id = 3049160;
                $param = array($remark['goods_title']);
                $action = "{$remark['goods_title']}回食得鲜商城来看看吧，签到送钱活动持续进行中哦！";
                break;
            case 'share_rewards':
                //分享新用户奖励@poptser
                $template_id = 3063191;
                $param = array($user_name);
                $action = "呼朋引伴，签到拿钱！您已成功邀请一位好友{$user_name}来食得鲜签到，邀请奖励1元钱已发至您在食得鲜的账户余额，请查收！您每天登陆也有1元钱喔";
                break;
            case 'delayed_order':
                //延迟订单@poptser
                $template_id = 3054461;
                $param =array($user_name,$order_sn,$remark['action'],$remark['best_time']);
                $action = "尊敬的".$user_name."，您的订单".$order_sn."由于".$remark['action']."已将配送延迟为".$remark['best_time']."，请耐心等待。可致电食得鲜客服400-8302-108，或通过食得鲜公众号联系客服。";
                break;
            case 'question_order':
                //问题订单@poptser
                $template_id = 3051380;
                $param =array($user_name,$order_sn,$remark['action'],$remark['best_time']);
                $action = "尊敬的".$user_name."，您的订单".$order_sn."因为".$remark['action']."进行延迟，配送时间延迟为".$remark['best_time']."，请耐心等待。可致电食得鲜客服400-8302-108，或通过食得鲜公众号联系客服。";
                break;
            case 'order_refund_by_model':
                //退货退款、缺货退款、次品退款@poptser
                $template_id = 3051379;
                $param = array($user_name,$remark['goods_name'],$remark['goods_num'],$remark['refund_type'],$remark['refund_amount']);
                $action = "尊敬的{$user_name}，您购买的{$remark['goods_name']}等{$remark['goods_num']}种商品因{$remark['refund_type']}为您退款；退款额{$remark['refund_amount']}将在1-3个工作日内返回原支付账号。可致电食得鲜客服400-8302-108，或通过食得鲜公众号联系客服。";
                break;
            case "receipt_verification" :
                //开始配送短信提醒并发送收货验证码@poptser
                $template_id = 3058129;
                $order_id=M("order_info")->where(array('order_sn'=>$order_sn))->getField("order_id");
                //移除楼小二相关
                $goods_name=M("order_goods")->where(array('order_id'=>$order_id,'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$order_id.')')))->limit(1)->getField("goods_name");
                $goods_number=M("order_goods")->where(array('order_id'=>$order_id,'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$order_id.')')))->count();
                $goods_l=" [ ".$goods_name." ] 等 ".$goods_number." 件商品";
                $code_text = "请将验证码 [ ".$remark['code']." ] 提供给配送员进行确认送达。";
                $param = array($user_name,$goods_l,$remark['phone'],$remark['best_time'],$code_text);
                $action = "尊敬的".$user_name."，您的商品".$goods_l."已经在配送中，配送员".$remark['phone']."，预计到达时间为".$remark['best_time']."，请保持手机畅通。请将验证码 [ ".$remark['code']." ] 提供给配送员进行确认送达。祝生活愉快！";
                break;
            default:
                return false;//参数错误
                break;
        }

        //$send_data = true;
        $my_id = S('template_id_'.$message_code);
        if(!$my_id){
            $my_id = M("mail_templates")->where(array("template_code"=>$message_code))->getField("template_id");
            S('template_id_'.$message_code,$my_id);
        }

        $weburl='';
        if(!empty($remark['url'])){
            $weburl=$remark['url'];
        }
        $message_log_id=$this->write_message_log($user_phone,9,$user_name,0,$user_id,$action,$my_id,$weburl,$order_sn);



        $this->send_app_wechat_sms_api($message_code,$user_id,$param,$param_voice,$wechat_param,$wechat_url,$message_log_id,$template_id,$phone);

        return $message_log_id;

    }

    public function get_louxiaoer_info($order_id){
        return M("louxiaoer_order")->alias("lo")->join("left join sdx_admin_user as sau on lo.louxiaoer_id=sau.user_id left join sdx_warehouse_personnel as swp on swp.uid=sau.user_id")->where(array('lo.order_id'=>$order_id))->field("swp.wechat_barcode_img,swp.name,sau.user_name as phone")->find();
    }



    /**
     * 写入记录短信发送记录
     * @param $phone
     * @param $state
     * @param $name
     * @param $role
     * @param $user_id
     * @param $message_tem
     * @param $templates_id
     */
    private function  write_message_log($phone, $state, $name, $role, $user_id, $message_tem, $templates_id,$weburl='',$order_sn){
        $message_log=array();
        $message_log['con_phone'] = $phone;
        $message_log['state'] = $state;
        $message_log['consignee'] = $name;
        $message_log['web_url'] = $weburl;
        $message_log['order_sn'] = $order_sn;

        /*$con_type = M("users")->where(array('user_id'=>$user_id))->getField('user_rank');

        if($con_type){
            $message_log['con_type'] = $con_type;
        }else{*/
        $message_log['con_type'] = 0;
        //}

        $message_log['user_id'] = $user_id;
        if(is_array($message_tem)){
            foreach($message_tem as $key=>$val){
                $message_log[$key] = $val;
            }
        }else{
            $message_log['send_content'] = $message_tem;
        }
        $message_log['templates_id'] = $templates_id;
        $message_log['send_time'] = local_date("Y-m-d H:i:s");

//        dd($message_log);
        return M("message_log")->add($message_log);
    }


    private function  update_message_log($message_id, $state_field,$state,$alimsg_id=0){
        if(!empty($state_field) && $state!=''){
            $message_log=array();
            $message_logw['message_id'] = $message_id;
            $message_log[$state_field] = $state;
            if($alimsg_id!=0){
                $message_log['alimsg_id'] = $alimsg_id;
            }

            M("message_log")->where($message_logw)->save($message_log);
        }
    }


    private function send_message_api_netease($template_id=null,$phone=array(),$param=array()){
        //return true;
        //网易云信短信发送测试
        //$phone = array("15820245055");
        //$param = array("name",'order_sn');
        //网易云信短信发送测试
        if (!empty($template_id)||!empty($phone)||!empty($param)){
            $data_mobile = json_encode($phone);
            $data_params = json_encode($param);
            $res = $this->requst($template_id,$data_mobile,$data_params);
            $send_re = json_decode($res,true);

            if($send_re['code']==200){
                return true;
            }else{
                $path= APP_PATH."Runtime/Logs/SDXApi/message.log";//接收文件目录
                $temp_file=file_put_contents($path, print_r($phone,true).print_r($param,true).print_r($send_re,true),FILE_APPEND);
                return false;
            }
        }else{
            return false;
        }
        //dump($html);
    }

    //阿里云短信
    private function send_message_api_taobao($template_id=null,$phone=array(),$param=array(),$extent='SDX',$sms_type='normal'){
        vendor('TaoBaoSdk.TopSdk');

        if(empty($template_id) || empty($phone) || empty($param)){
            return false;
        }

        $content = json_encode($param);
        $mobile = $phone[0];

        $tpclent = new \TopClient();
        $tpclent->appkey = C('ALIDAYU_APPKEY');
        $tpclent->secretKey = C('ALIDAYU_SECRETKEY');
        $tpclent->format='json';

        $SmsFreeSignName = C('SMSFREESIGNNAME');

        $req = new \AlibabaAliqinFcSmsNumSendRequest();

        $req->setExtend($extent);
        $req->setSmsType($sms_type); //短信类型
        $req->setSmsFreeSignName($SmsFreeSignName); //短信签名
        $req->setSmsParam($content);   //短信模板对应的变量数据
        $req->setRecNum($mobile); //接受短信手机号
        $req->setSmsTemplateCode($template_id); //短信模板ID
        $resp = $tpclent->execute($req);

        write_log('send_message_result['.$mobile.']['.$content.']: '.json_encode($resp),'sms');
        $result = $resp['result'];
        if($result['success']==true && $result['err_code']=='0'){
            return true;
        }else{
            return false;
        }

    }

    private function send_voice_message_api_taobao($template_id=null,$phone=array(),$param=array(),$extent='SDX',$sms_type='normal'){
        vendor('TaoBaoSdk.TopSdk');

        $content = json_encode($param);
        $mobile = $phone[0];
        $calledshownum = C('CALLEDSHOWNUM');

        if(empty($template_id) || empty($phone) || empty($param) || empty($calledshownum)){
            return false;
        }

        $tpclent = new \TopClient();
        $tpclent->appkey = C('ALIDAYU_APPKEY');
        $tpclent->secretKey = C('ALIDAYU_SECRETKEY');
        $tpclent->format='json';

        $req = new \AlibabaAliqinFcTtsNumSinglecallRequest();
        $req->setExtend($extent);
        $req->setTtsParam($content);
        $req->setCalledNum($mobile);
        $req->setCalledShowNum($calledshownum);
        $req->setTtsCode($template_id);
        $resp = $tpclent->execute($req);

        write_log('send_message_result['.$mobile.']['.$content.']: '.json_encode($resp),'voice_sms');
        $result = $resp['result'];
        if($result['success']==true && $result['err_code']=='0'){
            return true;
        }else{
            return false;
        }

    }

    public function checka(){
        set_time_limit(0);
        $next_openid=$_REQUEST['next_openid'];


        $weObj =  new TPWechat($this->options);
        $result=$weObj->getUserList($next_openid);

        $i=0;
        foreach($result['data']['openid'] as $item){
            $user=$weObj->getUserInfo($item);
            if(!empty($user['unionid'])&&!empty($item)){
                M("wechat_user")->where(array('unionid'=>$user['unionid']))->save(array('openid'=>$item));
            }

            $next_openid=$item;
            $i++;
            if($i>=1000){
                break;
            }
        }
        echo '<javascript language="JavaScript">location.href="index.php?s=/Smsapi/checka&next_openid='.$next_openid.'"</javascript>';


    }

    //微信推送
    public function wechat_template_send($user_id,$param=array(),$mail_templates,$wechat_url,$message_log_id){
        $users=M("wechat_user")->where(array("ect_uid"=>$user_id))->Field("openid")->find();


        if(!empty($users['openid']) && !empty($mail_templates['wechat_template_id'])){

            $wechatParam=array();

            foreach($param as $key=>$val){
                if(mb_strlen($val,'utf-8')>100 && $key!='url' && $mail_templates['message_code']!='bonus_expired_reminder'){
                    $val=mb_substr($val,0,100,"utf-8").'...';
                }
                if(is_array($val)){
                    $wechatParam[$key]=array('value'=>$val[0],'color'=>$val[1]);
                }else{
                    $wechatParam[$key]=array('value'=>$val,'color'=>"#173177");
                }

                $mail_templates['template_content']=preg_replace('/%s/', $val, $mail_templates['template_content'], 1);
            }

            if(!empty($mail_templates['push_title'])){
                $mail_templates['push_title'] = $this->additional ? $this->additional : $mail_templates['push_title'];
                $wechatParam['first']=array('value'=>$mail_templates['push_title'],'color'=>"#173177");
            }

            if(!empty($mail_templates['template_remark'])){
                $wechatParam['remark']=array('value'=>$mail_templates['template_remark'],'color'=>"#173177");
            }


            $data['touser']=$users['openid'];
            $data['template_id']=$mail_templates['wechat_template_id'];
            if(!empty($param['url'])){
                $data['url']=$param['url'];
            }
            if(!empty($mail_templates['click_push_act']) && $mail_templates['click_push_title']==3){
                $data['url']=$mail_templates['click_push_act'];
            }
            if(strpos($data['url'],'?')){
                $data['url'].="&utm_source=".$mail_templates['template_code'];
            }else{
                $data['url'].="?utm_source=".$mail_templates['template_code'];
            }

            /*if(!strpos($data['url'],'&code')){
                $code=md5($user_id.'sdx@9999');
                $data['url'].='&oid='.$user_id.'&code='.$code;
            }*/

            $data['data']=$wechatParam;
            $weObj =  new TPWechat($this->options);
            $result=$weObj->sendTemplateMessage($data);
            $resultArr=json_decode($result);

            $send_content=array();
            foreach($wechatParam as $key=>$li){
                $send_content[]=$key.'=>'.$li['value'];
            }
            $send_content_text=implode(" - ",$send_content);

            $this->update_message_log($message_log_id,'wechat_content', $send_content_text);


            if($resultArr->errcode=='0'){

                $this->update_message_log($message_log_id,'wechat_state', 1);
                return true;
            }else{
                $path= APP_PATH."Runtime/Logs/SDXApi/wechat_push.log";//接收文件目录
                file_put_contents($path, print_r($user_id,true).print_r($resultArr,true).print_r($param,true),FILE_APPEND);
                $this->update_message_log($message_log_id,'wechat_state', 0);
            }
        }else{
            $this->update_message_log($message_log_id,'wechat_state', 3);
        }

        return false;

    }

    //APP推送
    public function app_push($user_id,$param=array(),$mail_templates,$message_log_id){


        foreach($param as $key=>$item){
            $mail_templates['template_content']=preg_replace('/%s/', $item, $mail_templates['template_content'], 1);
        }


        if($this->additional){
            $mail_templates['template_content'] = $mail_templates['template_content'].$this->additional;
        }
        $this->update_message_log($message_log_id,'app_state', 2);


        //获取用户客户端系统、设备ID

        $alipush_user=M("alipush")->where(array("user_id"=>$user_id))->order("add_time desc")->Field("device_sn,device_type")->limit(1)->find();
        $device_sn =$alipush_user['device_sn'];
        $device_type =$alipush_user['device_type'];

        if(!empty($device_sn)){

            $ExtParameters=array(
                'ios'=>array('type'=>'message','parameter'=>''),
                'android'=>array('activity'=>'com.weechan.shidexianapp.activity.PushMessageActivity','parameter'=>'')
            );


            if(!empty($mail_templates['click_push_notify_type'])){
                $ExtParameters['android']['parameter']['_NOTIFY_TYPE_']=$mail_templates['click_push_notify_type'];
            }


            $response=$this->alipush(explode(",",$device_sn), $mail_templates['push_title'], $mail_templates['template_content'],$ExtParameters,$mail_templates['click_push_title'],$device_type);
            if(!$response->ResponseId){
                $this->update_message_log($message_log_id,'app_state', 0);
            }else{
                $this->update_message_log($message_log_id,'app_state', 2,$response->ResponseId);
            }
        }else{
            $this->update_message_log($message_log_id,'app_state', 3);
        }

    }

    private function alipush($device_sn,$title,$body,$ExtParameters=array(),$OpenType=1,$device_type){
        Vendor('alipush.aliyun-php-sdk-core.Config');
        // 设置你自己的AccessKeyId/AccessSecret/AppKey
        $accessKeyId = C("ALIPUSH_ACCESSKEYID");
        $accessSecret = C("ALIPUSH_ACCESSSECRET");
        $appKey = C("ALIPUSH_APPKEY");

        $iClientProfile = DefaultProfile::getProfile("cn-hangzhou", $accessKeyId, $accessSecret);

        $client = new DefaultAcsClient($iClientProfile);
        $request = new Push\PushRequest();

        // 推送目标
        $request->setAppKey($appKey);
        $request->setTarget("device"); //推送目标: device:推送给设备; account:推送给指定帐号,tag:推送给自定义标签; all: 推送给全部
        $request->setTargetValue(implode(",",$device_sn)); //根据Target来设定，如Target=device, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
        $request->setDeviceType(3); // 设备类型deviceType 取值范围为:0~3. iOS设备: 0; Android设备: 1; 全部: 3, 这是默认值.

        // 推送配置
        $request->setType(1); // 0:表示消息(默认为0), 1:表示通知
        $request->setTitle($title); // 消息的标题
        if($device_type=='Ios'){
            $request->setBody(" "); // 消息的内容
        }else{
            $request->setBody($body); // 消息的内容
        }

        $request->setSummary($body); // 通知的摘要


        // 推送配置: iOS
        $request->setiOSBadge("1"); // iOS应用图标右上角角标
        $request->setiOSMusic("default"); // iOS通知声音
        $request->setiOSTitle($title);//iOS通知标题(iOS 10+)
        $request->setiOSSubtitle(" ");//iOS通知副标题(iOS 10+)
        $request->setiOSMutableContent("true");//使能通知扩展处理(iOS 10+)
        $request->setiOSNotificationCategory("test_category");//设定通知Category(iOS 10+)
        if(!empty($ExtParameters['ios'])){
            $request->setiOSExtParameters(json_encode($ExtParameters['ios'])); //自定义的kv结构,开发者扩展用 针对iOS设备（iOS 10+可以使用attachment关键字来指定富媒体推送通知的资源Url）
        }
        $request->setApnsEnv("PRODUCT");
        $request->setRemind("true"); // 推送时设备不在线（既与移动推送的服务端的长连接通道不通），则这条推送会做为通知，通过苹果的APNs通道送达一次(发送通知时,Summary为通知的内容,Message不起作用)。注意：离线消息转通知仅适用于生产环境

        // 推送配置: Android
        if($OpenType!='1'){
            $OpenType='2';
        }
        $request->setAndroidOpenType($OpenType); // 点击通知后动作,1:打开应用 2: 打开应用Activity 3:打开 url 4 : 无跳转逻辑
        //$request->setAndroidOpenUrl($url); // Android收到推送后打开对应的url,仅仅当androidOpenType=3有效
        $request->setAndroidActivity($ExtParameters['android']['activity']);
        //$request->setsetXiaomiActivity("_Your_XiaoMi_Activity_");//设置该参数后启动小米托管弹窗功能，此处指定通知点击后跳转的Activity（托管弹窗的前提条件：1. 继承小米辅助通道；2. storeOffline设为true)

        if(!empty($ExtParameters['android']['parameter'])){
            $request->setAndroidExtParameters(json_encode($ExtParameters['android']['parameter'])); //设定android类型设备通知的扩展属性
        }

        // 推送控制
        $pushTime = gmdate('Y-m-d\TH:i:s\Z', strtotime('+3 second'));//延迟3秒发送
        $request->setPushTime($pushTime);
        $expireTime = gmdate('Y-m-d\TH:i:s\Z', strtotime('+1 day'));//设置失效时间为1天
        $request->setExpireTime($expireTime);
        $request->setTimeOut(3);
        $request->setStoreOffline("true"); // 离线消息是否保存,若保存, 在推送时候，用户即使不在线，下一次上线则会收到

        $response = $client->getAcsResponse($request);

        return $response;
    }





    private function requst($templateid,$mobiles,$params){
        $appKey = C("AppKey");
        $appSecret = C("AppSecret");
        $nonce = rand(100000,999999);
        $curTime = time();
        $checkSum = sha1($appSecret . $nonce . $curTime);
        $opts = array (
            'http' => array(
                'method' => 'POST',
                'header' => array(
                    'Content-Type:application/x-www-form-urlencoded;charset=utf-8',
                    "AppKey:$appKey",
                    "Nonce:$nonce",
                    "CurTime:$curTime",
                    "CheckSum:$checkSum"
                ),
                'content' =>  'templateid='.$templateid.'&mobiles='.$mobiles.'&params='.$params
            ),
        );
        //return $opts;
        $context = stream_context_create($opts);
        $html = file_get_contents(C('NETEASE_API_URL'), false, $context);
        //w_log("log",$html);
        return $html;
    }

    //微信推送(特制红包到期通知)
    public function wechat_template_send_bonus_expired_reminder($keyword1,$keyword2,$openid,$template_id,$dayS){

        $wechatParam=array();
        $wechatParam['first']=array('value'=>'陪你那么久，不想留遗憾！','color'=>"#173177");
        $wechatParam['remark']=array('value'=>'亲爱的主人，说好要做您的天使，可现在只能陪您最后'.$dayS.'天了！有效期内使用红包满减，让彼此不留遗憾','color'=>"#173177");
        $wechatParam['keyword1']=array('value'=>$keyword1,'color'=>"#173177");
        $wechatParam['keyword2']=array('value'=>$keyword2,'color'=>"#173177");

        $data['url']="https://w.shidexian.com/?index&utm_source=GZHbonus_expired_reminder";
        $data['touser']=$openid;
        $data['template_id']=$template_id;
        $data['data']=$wechatParam;
        $weObj =  new TPWechat($this->options);
        $result=$weObj->sendTemplateMessage($data);
        $resultArr=json_decode($result);

        if($resultArr->errcode=='0'){
            return true;
        }

        return false;
    }

    /**
     * 发送短信API(特制红包到期通知)
     * @param $message_code
     * @param $user_phone
     * @param null $user_name
     * @param int $user_rank
     * @param null $order_sn
     * @param null $ver_code
     * @return bool
     * @throws Exception
     */
    public function send_message_api_bonus_expired_reminder($bonus_list,$w_bonus=0){

        if(count($bonus_list)>1000){
            echo '单次推送不能超过1000条';
            exit();
        }

        $message_code='bonus_expired_reminder';

        //不发送短信
        $no_send = array(
            18028582275,18820013479,18903012888,13423621976,13922303379,
            13435247596,18588734970
        );

        $bonus_id_str=implode(",",$bonus_list);



        //$send_data = true;
        $mail_templates = S('mail_templates_'.$message_code);
        if(!$mail_templates){
            $mail_templates = M("mail_templates")->where(array("template_code"=>$message_code))->find();
            S('mail_templates_'.$message_code,$mail_templates,60);
        }

        $Model = new Model();
        $bonus_list=$Model->query("select a.device_sn,a.device_type,wu.nickname,wu.openid,bt.type_name,bt.bonus_discount_type,bt.type_money,bt.type_id,bt.min_goods_amount,bt.use_end_date,ub.bonus_sn,ub.bonus_id,ub.deadline,u.user_name,u.mobile_phone,u.user_id from sdx_user_bonus as ub left join sdx_bonus_type as bt on ub.bonus_type_id=bt.type_id left join sdx_users as u on u.user_id=ub.user_id left join sdx_wechat_user as wu on wu.ect_uid=u.user_id left join sdx_alipush as a on a.user_id=u.user_id where ub.used_time=0 and ub.bonus_id in(".$bonus_id_str.") group by ub.bonus_id");

        $insertSql=array();
        foreach($bonus_list as $item2){

            if(in_array($item2['mobile_phone'],$no_send)){
                continue;
            }

            $keyword1='';
            if($item2['bonus_discount_type']==1){
                $keyword1='满'.$item2['min_goods_amount'].'减'.$item2['type_money'].'红包';
            }elseif($item2['bonus_discount_type']==2){
                $keyword1=$item2['type_money'].'折红包';
            }

            if($item2['deadline']!=0){
                $keyword2=local_date("Y-m-d",$item2['deadline']);
            }else{
                $keyword2=local_date("Y-m-d",$item2['use_end_date']);
            }

            $betweenSecond=strtotime(date("Y-m-d"))-strtotime($keyword2);
            $dayS=$betweenSecond/(24*60*60);
            $dayS+=1;

            $wechat_state=false;
            //微信推送
            if(!empty($item2['openid'])){
                $wechat_state=$this->wechat_template_send_bonus_expired_reminder($keyword1,$keyword2,$item2['openid'],$mail_templates['wechat_template_id'],$dayS);
            }

            //短信推送
            $wechat_content='';
            $app_state=9;
            $state=9;
            $alimsg_id='';

            $send_content = "嗨，".$item2['nickname']."，你有满".$item2['min_amount']."减".$item2['bonus_money']."优惠券将于".$keyword2."到期，请及时使用。详情登录食得鲜公众号或APP“我的红包”查看。";

            if(!$wechat_state){


                if(preg_match("/^1[34578]\d{9}$/", $item2['mobile_phone'])){
                    if(empty($item['nickname'])){
                        $item['nickname']='食得鲜用户';
                    }

                    //send_message_api_netease
                    $template_id = 3060612;
                    $param =array($item['nickname'],$keyword1,$keyword2);


                    $data_mobile = json_encode($item2['mobile_phone']);
                    $data_params = json_encode($param);
                    $res = $this->requst($template_id,$data_mobile,$data_params);
                    $send_re = json_decode($res,true);

                    if($send_re['code']==200){
                        $state=1;
                    }else{
                        $state=0;
                    }
                }

                if(!empty($item2['device_sn'])){
                    $response=$this->alipush(array($item2['device_sn']),$mail_templates['push_title'],$send_content,array(),'1',$item2['device_type']);
                    if(!$response->ResponseId){
                        $app_state=2;
                        $alimsg_id=$response->ResponseId;
                    }
                }



            }else{
                $wechat_content='first=>陪你那么久，不想留遗憾！ - remark=>亲爱的主人，说好要做您的天使，可现在只能陪您最后'.$dayS.'天了！有效期内使用红包满减，让彼此不留遗憾 - keyword1=>'.$keyword1.' - keyword2=>'.$keyword2.' - url=>https://w.shidexian.com/?index&utm_source=GZHbonus_expired_reminder';

            }

            $wechat_state_t=9;
            if($wechat_state){
                $wechat_state_t=1;
            }

            $bonus_type_id=0;
            if($w_bonus==1){
                $bonus_type_id=$item2['type_id'];
            }


            //格式化短信
            if(empty($item2['nickname'])){
                $item2['nickname']='食得鲜用户';
            }
            $insertSql[]="('".$item2['mobile_phone']."',$state,$wechat_state_t,$app_state,'$alimsg_id','".$item2['nickname']."',0,".$item2['user_id'].",'$send_content','$wechat_content',".$mail_templates['template_id'].",'".local_date("Y-m-d H:i:s")."',$bonus_type_id)";
        }

        $insertSqlStr=implode(",",$insertSql);
        $Model->execute("insert into sdx_message_log (`con_phone`,`state`,wechat_state,app_state,alimsg_id,consignee,con_type,user_id,send_content,wechat_content,templates_id,send_time,bonus_type_id) VALUES ".$insertSqlStr."");

        return true;

    }



}
